// 语法：useEffect(setup, dependencies?)
// 目标：真是案例。利用useEffect的触发时机规则。进行输入用户ID,请求接口，实时更新组件数据的功能。

import { Input, message, Skeleton } from 'antd';
import { useEffect, useState } from 'react';
interface UserData {
  name: string;
  email: string;
  username: string;
  phone: string;
  website: string;
}

const App = () => {
  const [userId, setUserId] = useState('');
  const [userData, setUserData] = useState<UserData | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [errorTips, setErrorTips] = useState<number | null>(null);

  useEffect(() => {
    // fetch(`https://jsonplaceholder.typicode.com/users/${userId}`)
    //   .then((res) => res.json())
    //   .then((res) => {
    //     console.log(res, 'resxxx');
    //     setUserData(res);
    //   });
    // 优化：使用async/await
    const fetchUserData = async () => {
      setErrorTips(null);
      setIsLoading(true);
      setUserData(null);
      try {
        const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
        console.log(res, 'resxxx');
        const { ok, statusText, status } = res;
        if (!ok) {
          message.error(`请求出错！${statusText}`);
          setErrorTips(status);
          return;
        }
        const data = await res.json();
        setUserData(data);
      } catch (error: any) {
        console.log(error, 'error');
        setErrorTips(error.message);
      } finally {
        setIsLoading(false);
      }
    };

    const timer = setTimeout(() => {
      if (userId) {
        fetchUserData();
      }
    }, 500);
    return () => {
      clearTimeout(timer);
    };
  }, [userId]);

  const changeUserId = (e: React.ChangeEvent<HTMLInputElement>) => {
    setUserId(e.target.value);
  };

  return (
    <>
      <Input placeholder="输入userId" value={userId} onChange={(e) => changeUserId(e)} />
      {isLoading && <Skeleton />}
      {errorTips && <p>错误{errorTips}</p>}
      <h3>用户信息：</h3>
      {userData && !isLoading && (
        <div>
          <p>name: {userData.name}</p>
          <p>email: {userData.email}</p>
          <p>username: {userData.username}</p>
          <p>phone: {userData.phone}</p>
          <p>website: {userData.website}</p>
        </div>
      )}
    </>
  );
};

export default App;
